﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DevComponents.Editors;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using System.IO;
using System.Collections.Specialized;
using ESRI.ArcGIS.Carto;
using Dundas.Charting.WinControl;
using PlanningGIS.Framework.Rule;
using PlanningGIS.Win.Controls;
using PlanningGIS.Framework;
using PlanningGIS.Util.Management;
using PlanningGIS.Util.Win32;
using PlanningGIS.ArcGIS;

namespace PlanningGIS.Statistics
{
    /// <summary>
    /// 名    称：frmYSSLTJ
    /// 作    用：要素统计对话框
    /// 开发人员：张利勇
    /// 开发日期：2010-04-15
    /// 修改人员：
    /// 修改日期：
    /// 修改说明：
    /// </summary>
    public partial class frmYSSLTJ : Office2007Form
    {
        public string m_sDanWei = "";   //单位最好为空
        public IMap m_pMap = null;
        private ILayer m_pLayer = null;
        private int LastIndex;
        private List<ILayer> m_FeatureLayerList = new List<ILayer>();
        int fcodeFieldIndex = -1;   //分类代码属性对应的字段序号
        int fcodeItemIndex = -1;    //要素类别所在cboField.Items中的序号

        public IApplication m_Application { get; set; }

        /// <summary>
        /// 图层选择类型数组
        /// </summary>
        private string[] selectMethodArray = { "<所有图层>", "<可见图层>" };

        public frmYSSLTJ()
        {
            InitializeComponent();
        }

        private void frmGTKJZHPY_Load(object sender, EventArgs e)
        {
            this.Text = "要素统计";
            cboShi.Tag = true;
            IniChartType();
            cboShi.SelectedIndex = 4;
            cboShi.Tag = false;

            cboShi.Visible = true;
            cmdSaveShiPic.Visible = true;

            cboClass.NodesExpand = selectMethodArray;
            cboClass.OnCreate((m_Application as IFramework).Object);           

            m_FeatureLayerList = MapHelper.GetAllLayer(m_pMap);
            cboClass.SelectedIndex = 0;
        }
                

        private void IniFieldClass()
        {
            fcodeFieldIndex = -1;   //分类代码属性对应的字段序号
            fcodeItemIndex = -1;    //要素类别所在cboField.Items中的序号
            if (cboClass.SelectedIndex > 1)
            {
                cboField.Items.Clear();

                IFeatureLayer pFeatLayer = cboClass.SelectedLayer as IFeatureLayer;
                ITable pTable = pFeatLayer.FeatureClass as ITable;
                for (int i = 0; i < pTable.Fields.FieldCount; i++)
                {
                    IField pField = pTable.Fields.get_Field(i);
                    if (pField.Type == esriFieldType.esriFieldTypeString)
                    {
                        DevComponents.Editors.ComboItem comboItem = new ComboItem();
                        comboItem.Tag = pField.Name;
                        comboItem.Text = pField.AliasName;
                        cboField.Items.Add(comboItem);

                        if (pField.AliasName.ToLower() == "fcode" || pField.AliasName == "分类代码")
                        {
                            fcodeFieldIndex = i;
                            fcodeItemIndex = cboField.Items.Count;

                            DevComponents.Editors.ComboItem comboItemFcode = new ComboItem();
                            comboItemFcode.Tag = pField.Name;
                            comboItemFcode.Text = "要素类别";
                            cboField.Items.Add(comboItemFcode);
                        }
                    }
                }

                if (fcodeItemIndex >= 0)
                {
                    cboField.SelectedIndex = fcodeItemIndex;
                }
                else if (cboField.Items.Count > 0)
                {
                    cboField.SelectedIndex = 0;
                }
            }
        }

        private void cboClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            fcodeFieldIndex = -1;   //分类代码属性对应的字段序号
            fcodeItemIndex = -1;    //要素类别所在cboField.Items中的序号

            if (cboClass.SelectedIndex == 0)
            {
                cboField.Items.Clear();
                cboField.Text = "";
                StatisFeatureLayers(false);
            }
            else if (cboClass.SelectedIndex == 1)
            {
                cboField.Items.Clear();
                cboField.Text = "";
                StatisFeatureLayers(true);
            }
            else
            {
                IniFieldClass();
            }
        }

        private void StatisFeatureLayers(bool bOnlyVisibleLevels)
        {
            grdShi.Rows.Clear();

            try
            {
                grdShi.Columns[0].HeaderText = "图层名";
                List<string> FeatValue = new List<string>();//各地物类的名称
                List<int> FeatCounts = new List<int>();     //各地物类的个数
                int FeatClsIndex = -1;
                int AllFeatCount = 0;
                string s = null;

                for (int i = 0; i < m_FeatureLayerList.Count; i++)
                {
                    IFeatureLayer featureLayer = m_FeatureLayerList[i] as IFeatureLayer;
                    if (featureLayer == null || featureLayer.FeatureClass == null) continue;
                    if (bOnlyVisibleLevels)
                    {
                        if (featureLayer.Visible)
                        {
                            FeatClsIndex++;
                            FeatValue.Add(featureLayer.Name);
                            FeatCounts.Add((featureLayer as IFeatureLayer).FeatureClass.FeatureCount(null));
                        }
                    }
                    else
                    {
                        FeatClsIndex++;
                        FeatValue.Add(featureLayer.Name);
                        FeatCounts.Add(featureLayer.FeatureClass.FeatureCount(null));
                    }
                }

                for (int i = 0; i < FeatValue.Count; i++)
                {
                    grdShi.Rows.Add();
                    grdShi.Rows[i].Cells[0].Value = FeatValue[i];
                    grdShi.Rows[i].Cells[1].Value = FeatCounts[i].ToString();
                    AllFeatCount += FeatCounts[i];
                }

                txtSheng.Text = AllFeatCount.ToString();

                //BuildChartXian();
                BuildChartShi();

                LastIndex = cboClass.SelectedIndex;
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
        }

        private void cboField_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboField.Items.Count == 0) return;

            grdShi.Rows.Clear();

            try
            {
                //如果当前字段下拉框选择是“要素类别”，则按照分类代码赋要素类别
                if ((fcodeItemIndex >= 0) && (fcodeItemIndex == cboField.SelectedIndex)) 
                {
                    DataImportRule CurrentDataImportRule = GetCurrentDataImportRule();
                    if (CurrentDataImportRule == null) return;

                    grdShi.Columns[0].HeaderText = "要素类别";
                    IFeatureLayer pFeatLayer = cboClass.SelectedLayer as IFeatureLayer;
                    ITable pTable = pFeatLayer as ITable;
                    if (pTable.RowCount(null) > 10000)
                    {
                        if (MsgHelper.ShowYesOrNoQueryMsgBox("图层要素记录超过10000个，统计会花很长时间，您要继续统计该图层要素吗？") == DialogResult.No)
                            return;
                    }

                    int FieldIndex = fcodeFieldIndex;
                    string Field = pTable.Fields.get_Field(fcodeFieldIndex).Name;

                    ITableSort pTableSort = new TableSortClass();
                    pTableSort.Table = pTable;
                    pTableSort.Fields = Field;
                    pTableSort.Sort(null);

                    ICursor pCursor = pTableSort.Rows;
                    List<string> FeatValue = new List<string>();//各地物类的名称
                    List<int> FeatCounts = new List<int>();     //各地物类的个数
                    int FeatClsIndex = -1;
                    int AllFeatCount = 0;
                    string s = null;

                    IRow pRow = pCursor.NextRow();
                    while (pRow != null)
                    {
                        if (pRow.get_Value(FieldIndex).ToString() != s)
                        {
                            FeatClsIndex++;
                            s = pRow.get_Value(FieldIndex).ToString();
                            FeatValue.Add(ConvertFcode2Fname(s, CurrentDataImportRule));
                            FeatCounts.Add(1);
                        }
                        else
                        {
                            FeatCounts[FeatClsIndex]++;
                        }

                        pRow = pCursor.NextRow();
                    }

                    for (int i = 0; i < FeatValue.Count; i++)
                    {
                        grdShi.Rows.Add();
                        grdShi.Rows[i].Cells[0].Value = FeatValue[i];
                        grdShi.Rows[i].Cells[1].Value = FeatCounts[i].ToString();
                        AllFeatCount += FeatCounts[i];
                    }

                    txtSheng.Text = AllFeatCount.ToString();

                    //BuildChartXian();
                    BuildChartShi();
                }
                else
                {
                    string Field = ((ComboItem)cboField.SelectedItem).Tag.ToString();
                    grdShi.Columns[0].HeaderText = "属性值";
                    IFeatureLayer pFeatLayer = m_FeatureLayerList[cboClass.SelectedIndex - 2] as IFeatureLayer;
                    ITable pTable = pFeatLayer as ITable;
                    if (pTable.RowCount(null) > 10000)
                    {
                        if (MsgHelper.ShowYesOrNoQueryMsgBox("图层要素记录超过10000个，统计会花很长时间，您要继续统计该图层要素吗？") == DialogResult.No)
                            return;
                    }

                    int FieldIndex = pTable.Fields.FindField(Field);
                    ITableSort pTableSort = new TableSortClass();
                    pTableSort.Table = pTable;

                    pTableSort.Fields = Field;
                    pTableSort.Sort(null);

                    ICursor pCursor = pTableSort.Rows;
                    List<string> FeatValue = new List<string>();//各地物类的名称
                    List<int> FeatCounts = new List<int>();     //各地物类的个数
                    int FeatClsIndex = -1;
                    int AllFeatCount = 0;
                    string s = null;

                    IRow pRow = pCursor.NextRow();
                    while (pRow != null)
                    {
                        if (pRow.get_Value(FieldIndex).ToString() != s)
                        {
                            FeatClsIndex++;
                            s = pRow.get_Value(FieldIndex).ToString();
                            FeatValue.Add(s);
                            FeatCounts.Add(1);
                        }
                        else
                        {
                            FeatCounts[FeatClsIndex]++;
                        }

                        pRow = pCursor.NextRow();
                    }

                    for (int i = 0; i < FeatValue.Count; i++)
                    {
                        grdShi.Rows.Add();
                        grdShi.Rows[i].Cells[0].Value = FeatValue[i];
                        grdShi.Rows[i].Cells[1].Value = FeatCounts[i].ToString();
                        AllFeatCount += FeatCounts[i];
                    }

                    txtSheng.Text = AllFeatCount.ToString();

                    //BuildChartXian();
                    BuildChartShi();
                }
                LastIndex = cboClass.SelectedIndex;
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
        }

        #region 与检查规则有关的函数（涉及到类的重构参数改变都放在这里）

        /// <summary>
        /// 获取当前质检规则
        /// </summary>
        /// <returns></returns>
        public static DataImportRule GetCurrentDataImportRule()
        {
            DataImportRule dataImportRuleCur = null;
            foreach (DataImportRule dataImportRule in RuleConfig.DataBuilding.BuildingRules)
            {
                if (dataImportRule.RuleName == AppConfig.SystemConfig.符号化.默认规则)
                {
                    dataImportRuleCur = dataImportRule;
                    break;
                }
            }

            if (dataImportRuleCur == null)
            {
                if (RuleConfig.DataBuilding.BuildingRules.Count > 0)
                {
                    return RuleConfig.DataBuilding.BuildingRules[0];
                }
                else
                {
                    //throw new Exception("未找到当前数据入库规则，请检查入库规则！");
                    return null;
                }
            }

            return dataImportRuleCur;
        }
        #endregion

        /// <summary>
        /// 读取入库规则，将Fcode转化为对应的Fname，即要素类别；如果入库规则中找不到相应的Fcode，则返回Fcode
        /// </summary>
        /// <param name="Fcode"></param>
        /// <returns></returns>
        private string ConvertFcode2Fname(string Fcode, DataImportRule dataImportRule)
        {
            for (int i = 0; i < dataImportRule.dlgTargetFeatureClasses.Count; i++)
            {
                for (int j = 0; j < dataImportRule.dlgTargetFeatureClasses[i].featureCodes.Count; j++)
                {
                    if (dataImportRule.dlgTargetFeatureClasses[i].featureCodes[j].FCODE == Fcode)
                        return dataImportRule.dlgTargetFeatureClasses[i].featureCodes[j].FNAME;
                }
            }

            return Fcode;
        }

        private void BuildChartShi()
        {
            Dundas.Charting.WinControl.Chart chartTemp = chartShi;

            chartTemp.Series.Clear();
            chartTemp.Titles.Clear();

            chartTemp.Titles.Add(cboClass.Text + "要素数量统计图");
            chartTemp.Titles[0].Font = new System.Drawing.Font("宋体", 11);

            double dblMaxVal = 0;
            if ((int)((DevComponents.Editors.ComboItem)cboShi.SelectedItem).Tag == 6)
            {
                List<double> yval = new List<double>();
                List<string> yval1 = new List<string>();
                List<string> xval = new List<string>();
                double TotalNum = Convert.ToDouble(txtSheng.Text);
                chartTemp.Series.Clear();
                double pnum = 101800 / 101895.52;
                chartTemp.Series.Add("数量比率图");
                for (int i = 0; i < grdShi.RowCount; i++)
                {
                    int FeatCount = Convert.ToInt32(grdShi.Rows[i].Cells[1].Value);
                    yval1.Add((FeatCount * pnum).ToString("#####.##"));
                    yval.Add(FeatCount * pnum);
                    xval.Add(grdShi.Rows[i].Cells[0].Value.ToString());
                }
                chartTemp.Series[0].Type = SeriesChartType.Pie;
                chartTemp.ChartAreas[0].Area3DStyle.Enable3D = true;
                chartTemp.Series[0].Points.DataBindXY(xval.ToArray(), yval.ToArray());
            }
            else
            {
                List<string> LayerNames = new List<string>();
                for (int i = 0; i < grdShi.RowCount; i++)
                {
                    //给定series系列的名字
                    string strSeriesName = grdShi.Rows[i].Cells[0].Value.ToString();
                    //如果有重复的Layername，增加一个数字，进行区分
                    if (LayerNames.Contains(strSeriesName))
                    {
                        int Layernamecount = 0;
                        for (int j = 0; j < LayerNames.Count; j++)
                        {
                            if (LayerNames[j] == strSeriesName)
                            {
                                Layernamecount++;
                            }
                        }
                        LayerNames.Add(strSeriesName);
                        strSeriesName += "_" + Layernamecount.ToString();
                    }
                    else
                    {
                        LayerNames.Add(strSeriesName);
                    }
                    chartTemp.Series.Add(strSeriesName);
                    chartTemp.Series[i]["PointWidth"] = "1.5";
                    chartTemp.Series[i].ShowLabelAsValue = true;
                    chartTemp.Series[i]["BarLabelStyle"] = "Center";
                    switch ((int)((DevComponents.Editors.ComboItem)cboShi.SelectedItem).Tag)
                    {
                        case 0:
                        case 1:
                            chartTemp.Series[i]["DrawingStyle"] = "Default";
                            break;
                        case 2:
                        case 3:
                            chartTemp.Series[i]["DrawingStyle"] = "Emboss";
                            break;
                        case 4:
                        case 5:
                            chartTemp.Series[i]["DrawingStyle"] = "Cylinder";
                            break;
                    }
                    switch ((int)((DevComponents.Editors.ComboItem)cboShi.SelectedItem).Tag)
                    {
                        case 0:
                        case 2:
                        case 4:
                            chartTemp.Series[i].Type = SeriesChartType.Column;
                            break;
                        case 1:
                        case 3:
                        case 5:
                            chartTemp.Series[i].Type = SeriesChartType.Bar;
                            break;
                    }

                    double[] yval = new double[1];
                    string[] xval = new string[1];
                    yval[0] = Convert.ToDouble(grdShi.Rows[i].Cells[1].Value);
                    xval[0] = grdShi.Rows[i].Cells[0].Value.ToString();

                    if (yval[0] > dblMaxVal)
                    {
                        dblMaxVal = yval[0];
                    }

                    chartTemp.Series[i].Points.DataBindXY(xval, yval);
                    chartTemp.Series[i].ShowLabelAsValue = false;
                }

                chartTemp.ChartAreas[0].AxisX.MinorGrid.Enabled = true;
                chartTemp.ChartAreas[0].AxisX.MajorGrid.Interval = 2;

                chartTemp.ChartAreas[0].AxisX.Title = "";
                chartTemp.ChartAreas[0].AxisY.Title = m_sDanWei;
                chartTemp.ChartAreas[0].AxisY.TitleAlignment = StringAlignment.Far;

                chartTemp.ChartAreas[0].Area3DStyle.Enable3D = false;
                chartTemp.ChartAreas[0].AxisX.LabelStyle.Enabled = false;
                chartTemp.ChartAreas[0].AxisY.Maximum = dblMaxVal * 1.1;
            }
        }

        private void cmdOK_Click(object sender, EventArgs e)
        {
            this.Close(); 
        }

        private void cmdSaveShiTab_Click(object sender, EventArgs e)
        {
            DevComponents.DotNetBar.Controls.DataGridViewX dataGridView1 = grdShi;
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //cmdExport.Enabled = false;
                //cmdCancel.Enabled = false;
                string FileName = saveFileDialog1.FileName;
                try
                {
                    FileInfo fi = new FileInfo(FileName);
                    if (fi.Exists)
                        fi.Delete();
                }
                catch (Exception ex)
                {
                    MsgHelper.ShowErrorMsgbox(ex.Message + "，导出失败！");
                    //cmdExport.Enabled = true;
                    //cmdCancel.Enabled = true;
                    return;
                }

                string strPath;
                //if (OSHelper.CheckExcel(out strPath) == false)
                //{
                //    MsgHelper.ShowErrorMsgbox("检测到您的电脑上未安装2003或以上版本的Excel！");
                //    return;
                //}

                try
                {
                    
                    ComObject pExcel = null;
                    try
                    {
                        pExcel = ComObject.CreateComInstance("Excel.Application");
                    }
                    catch (Exception ex)
                    {
                        MsgHelper.ShowWarningMsgbox("无法创建Excel对象，请检查是否已安装Excel 2003或以上的版本！");
                        return;
                    }

                    this.Cursor = Cursors.WaitCursor;
                    ComObject workBooks = ComObject.CreateInstance(pExcel["Workbooks"]);
                    ComObject pWorkbook = ComObject.CreateInstance(workBooks.InvokeMethod("Add"));

                    ComObject pWorksheet = ComObject.CreateInstance(pWorkbook["Worksheets", 1]);
                    pExcel["Visible"] = false;

                    for (int i = 0; i < dataGridView1.Columns.Count; i++)
                    {
                        //pWorksheet.Cells[1, i + 1] = dataGridView1.Columns[i].Name;
                        ComObject pRange = ComObject.CreateInstance(pWorksheet["Cells", 1, i + 1]);
                        pRange["Value2"] = dataGridView1.Columns[i].Name;
                    }

                    for (int j = 0; j < dataGridView1.Rows.Count; j++)
                    {
                        for (int k = 0; k < dataGridView1.Rows[j].Cells.Count; k++)
                        {
                            if (dataGridView1.Rows[j].Cells[k].Value != null)
                            {
                                //pWorksheet.Cells[j + 2, k + 1] = dataGridView1.Rows[j].Cells[k].Value.ToString();
                                ComObject pRange = ComObject.CreateInstance(pWorksheet["Cells", j + 2, k + 1]);
                                pRange["Value2"] = dataGridView1.Rows[j].Cells[k].Value.ToString();
                            }
                        }
                    }

                    //btnExport.Enabled = true;
                    //btnCancel.Enabled = true;
                    SaveAs(FileName, pWorkbook);
                    pExcel.InvokeMethod("Quit");
                    //System.Runtime.InteropServices.Marshal.ReleaseComObject(pExcel);
                    pExcel = null;
                    //System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkbook);
                    pWorkbook = null;
                    //System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorksheet);
                    pWorksheet = null;
                    MsgHelper.ShowInfomationMsgbox("导出成功！");
                }
                catch (Exception ex)
                {
                    MsgHelper.ShowWarningMsgbox("导出失败：" + ex.Message);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }

        private void cmdSaveShiPic_Click(object sender, EventArgs e)
        {
            // Create a new save file dialog
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            // Sets the current file name filter string, which determines 
            // the choices that appear in the "Save as file type" or 
            // "Files of type" box in the dialog box.
            saveFileDialog1.Filter = "Bitmap (*.bmp)|*.bmp|JPEG (*.jpg)|*.jpg|EMF (*.emf)|*.emf|PNG (*.png)|*.png|SVG (*.svg)|*.svg|GIF (*.gif)|*.gif|TIFF (*.tif)|*.tif";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;

            // Set image file format
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ChartImageFormat format = ChartImageFormat.Bmp;

                if (saveFileDialog1.FileName.EndsWith("bmp"))
                {
                    format = ChartImageFormat.Bmp;
                }
                else if (saveFileDialog1.FileName.EndsWith("jpg"))
                {
                    format = ChartImageFormat.Jpeg;
                }
                else if (saveFileDialog1.FileName.EndsWith("emf"))
                {
                    format = ChartImageFormat.Emf;
                }
                else if (saveFileDialog1.FileName.EndsWith("gif"))
                {
                    format = ChartImageFormat.Gif;
                }
                else if (saveFileDialog1.FileName.EndsWith("png"))
                {
                    format = ChartImageFormat.Png;
                }
                else if (saveFileDialog1.FileName.EndsWith("tif"))
                {
                    format = ChartImageFormat.Tiff;
                }
                else if (saveFileDialog1.FileName.EndsWith("svg"))
                {
                    format = ChartImageFormat.Svg;
                }

                // Save image
                chartShi.SaveAsImage(saveFileDialog1.FileName, format);
                MsgHelper.ShowInfomationMsgbox("保存图片成功！");
            }
        }

        private void cmdExport_Click(object sender, EventArgs e)
        {
            DevComponents.DotNetBar.Controls.DataGridViewX dataGridView1 = grdShi;
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //cmdExport.Enabled = false;
                //cmdCancel.Enabled = false;
                string FileName = saveFileDialog1.FileName;
                try
                {
                    FileInfo fi = new FileInfo(FileName);
                    if (fi.Exists)
                        fi.Delete();
                }
                catch (Exception ex)
                {
                    MsgHelper.ShowErrorMsgbox(ex.Message + "，导出失败！");
                    return;
                }

                string strPath;
                //if (OSHelper.CheckExcel(out strPath) == false)
                //{
                //    MsgHelper.ShowErrorMsgbox("检测到您的电脑上未安装2003或以上版本的Excel！");
                //    return;
                //}

                try
                {
                    
                    ComObject pExcel = null;
                    try
                    {
                        pExcel = ComObject.CreateComInstance("Excel.Application");
                    }
                    catch (Exception ex)
                    {
                        MsgHelper.ShowWarningMsgbox("无法创建Excel对象，请检查是否已安装Excel 2003或以上的版本！");
                        return;
                    }

                    this.Cursor = Cursors.WaitCursor;
                    ComObject workBooks = ComObject.CreateInstance(pExcel["Workbooks"]);
                    ComObject pWorkbook = ComObject.CreateInstance(workBooks.InvokeMethod("Add"));

                    ComObject pWorksheet = ComObject.CreateInstance(pWorkbook["Worksheets", 1]);
                    pExcel["Visible"] = false;
                    ComObject pRange;

                    for (int i = 0; i < dataGridView1.Columns.Count; i++)
                    {
                        //pWorksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 1, i + 1]);
                        pRange["Value2"] = dataGridView1.Columns[i].HeaderText;
                    }


                    for (int j = 0; j < dataGridView1.Rows.Count; j++)
                    {
                        for (int k = 0; k < dataGridView1.Rows[j].Cells.Count; k++)
                        {
                            if (dataGridView1.Rows[j].Cells[k].Value != null)
                            {
                                //pWorksheet.Cells[j + 2, k + 1] = dataGridView1.Rows[j].Cells[k].Value.ToString();
                                pRange = ComObject.CreateInstance(pWorksheet["Cells", j + 2, k + 1]);
                                pRange["Value2"] = dataGridView1.Rows[j].Cells[k].Value.ToString();
                            }
                        }
                    }
                    //pWorksheet.Cells[dataGridView1.Rows.Count + 2, 1] = "合计";
                    //pWorksheet.Cells[dataGridView1.Rows.Count + 2, 2] = txtSheng.Text;

                    pRange = ComObject.CreateInstance(pWorksheet["Cells", dataGridView1.Rows.Count + 2, 1]);
                    pRange["Value2"] = "合计";
                    pRange = ComObject.CreateInstance(pWorksheet["Cells", dataGridView1.Rows.Count + 2, 2]);
                    pRange["Value2"] = txtSheng.Text;

                    SaveAs(FileName, pWorkbook);
                    pExcel.InvokeMethod("Quit");
                    //System.Runtime.InteropServices.Marshal.ReleaseComObject(pExcel);
                    pExcel = null;
                    //System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkbook);
                    pWorkbook = null;
                    //System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorksheet);
                    pWorksheet = null;

                    MsgHelper.ShowInfomationMsgbox("导出成功！");
                }
                catch (Exception ex)
                {
                    MsgHelper.ShowWarningMsgbox("导出失败：" + ex.Message);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }

        private void SaveAs(string FileName, ComObject workBook)
        {
            int pXlFileFormat = -4143;
            string kong1 = "";
            string kong2 = "";
            bool False1 = false;
            bool False2 = false;
            int pXlSaveAsAccessMode = 1;
            int pXlSaveConflictResolution = 2;
            bool False3 = false;
            object null1 = null;
            object null2 = null;
            bool False4 = false;

            object[] objArr = new object[12];
            objArr[0] = FileName;
            objArr[1] = pXlFileFormat;
            objArr[2] = kong1;
            objArr[3] = kong2;
            objArr[4] = False1;
            objArr[5] = False2;
            objArr[6] = pXlSaveAsAccessMode;
            objArr[7] = pXlSaveConflictResolution;
            objArr[8] = False3;
            objArr[9] = null1;
            objArr[10] = null2;
            objArr[11] = False4;

            workBook.InvokeMethod("SaveAs", objArr);
        }

        private void cboShi_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((bool)cboShi.Tag == true)
            {
                return;
            }
            BuildChartShi();
        }

        private void IniChartType()
        {
            DevComponents.Editors.ComboItem comboItem= null;
            DevComponents.DotNetBar.Controls.ComboBoxEx cbo = null;

            //市图表样式
            cbo = cboShi;

            comboItem = new ComboItem();
            comboItem.Text = "柱状图";
            comboItem.Tag = 0;
            cbo.Items.Add(comboItem);

            comboItem = new ComboItem();
            comboItem.Text = "柱状图(横向)";
            comboItem.Tag = 1;
            cbo.Items.Add(comboItem);

            comboItem = new ComboItem();
            comboItem.Text = "方柱图";
            comboItem.Tag = 2;
            cbo.Items.Add(comboItem);

            comboItem = new ComboItem();
            comboItem.Text = "方柱图(横向)";
            comboItem.Tag = 3;
            cbo.Items.Add(comboItem);

            comboItem = new ComboItem();
            comboItem.Text = "圆柱图";
            comboItem.Tag = 4;
            cbo.Items.Add(comboItem);

            comboItem = new ComboItem();
            comboItem.Text = "圆柱图(横向)";
            comboItem.Tag = 5;
            cbo.Items.Add(comboItem);

            comboItem = new ComboItem();
            comboItem.Text = "饼图";
            comboItem.Tag = 6;
            cbo.Items.Add(comboItem);

            //comboItem = new ComboItem();
            //comboItem.Text = "饼图(3D)";
            //comboItem.Tag = 7;
            //cbo.Items.Add(comboItem);
        }

        private void tabMain_TabIndexChanged(object sender, EventArgs e)
        {

        }
        
        private bool IsWsSde(IFeatureClass pFeatCls)
        {
            IDataset pDs = pFeatCls as IDataset;
            IWorkspace pWs = pDs.Workspace;
            if (pWs.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
                return true;
            else
                return false;
        }

        private void chartXian_GetToolTipText(object sender, ToolTipEventArgs e)
        {
            switch (e.HitTestResult.ChartElementType)
            {
                case ChartElementType.DataPoint:
                    e.Text = e.HitTestResult.Series.Points[e.HitTestResult.PointIndex].AxisLabel  + ":" + e.HitTestResult.Series.Points[e.HitTestResult.PointIndex].YValues[0].ToString();
                    break;
                default :
                    break;
            }
        }

        private void chartShi_GetToolTipText(object sender, ToolTipEventArgs e)
        {
            switch (e.HitTestResult.ChartElementType)
            {
                case ChartElementType.DataPoint:
                    e.Text =e.HitTestResult.Series.Name +":"+ e.HitTestResult.Series.Points[e.HitTestResult.PointIndex].YValues[0].ToString();
                    break;
                default:
                    break;
            }
        }

        private void labelX2_Click(object sender, EventArgs e)
        {

        }
    }
}